<template>
  <div class="login-page" @keyup.enter="submitForm">
    <div class="login-box">
      <h1>欢迎登录心灵课堂</h1>
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="'账\xa0\xa0\xa0\xa0号'" prop="accountNumber">
          <el-input placeholder="请输入账号" prefix-icon="el-icon-user" type="text" v-model="ruleForm.accountNumber"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item :label="'密\xa0\xa0\xa0\xa0码'" prop="passWord">
          <el-input show-password placeholder="请输入密码" prefix-icon="el-icon-lock" type="password" v-model="ruleForm.passWord"
                    autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="validateCode">
          <div class="captcha-box">
            <el-input placeholder="请输入验证码" prefix-icon="el-icon-s-check" type="text"
                      v-model.number="ruleForm.validateCode"></el-input>
            <button id="validateCodeButton" type="button" @click="changeValidateCode">
              <img class="validateCodeImg" v-bind:src="validateCodeUrl">
            </button>
          </div>
        </el-form-item>
        <el-form-item id="button-form-item">
          <el-button id="el-button-a" type="primary" @click="submitForm">登录</el-button>
          <!--v-bind:disabled="!ruleForm.isFormValid"-->
          <el-button id="el-button-b" @click="resetForm">重置</el-button>
          <el-button id="el-button-c" type="danger" @click="goRegister">我要注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {validatePassWord} from '../../utils/validate'
import {login} from '../../request/api'

export default {
  data: function () {
    return {
      rules: {
        accountNumber: [
          {
            required: true, // 必填
            message: '请输入账号', // 没有填时提示语
            trigger: 'blur'
          },
          {
            pattern: /^\d+$/,
            message: '账号只能包含数字',
            trigger: 'blur'
          },
          {
            max: 16,
            min: 8,
            message: '账号长度需在8-16位之间',
            trigger: 'blur'
          }
        ],
        passWord: [
          {
            required: true, // 必填
            message: '请输入密码', // 没有填时提示语
            trigger: 'blur'
          },
          {
            max: 20,
            min: 6,
            message: '密码长度需在6-20位之间',
            trigger: 'blur'
          },
          {
            validator: validatePassWord,
            trigger: 'blur'
          }
        ],
        validateCode: [
          {
            required: true, // 必填
            message: '请输入验证码', // 没有填时提示语
            trigger: 'blur'
          }
        ]
      },
      ruleForm: {
        isFormValid: false, // 标志表单是否通过验证
        accountNumber: null,
        passWord: null,
        validateCode: null
      },
      validateCodeUrl: 'http://localhost:8080/VerificationCode/getVerificationCode?timestamp=' + Date.now().toString()
    }
  },
  methods: {
    submitForm: function () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 表单通过验证，执行登录操作
          login('/user/login', {
            accountNumber: this.ruleForm.accountNumber,
            passWord: this.ruleForm.passWord,
            validateCode: this.ruleForm.validateCode
          }).then(resp => {
            if (resp.responseCode === 20004) {
              this.$message({
                message: '登录成功',
                type: 'success',
                duration: 3000
              })
              // 存储用户信息
              sessionStorage.setItem('userInfo', JSON.stringify(resp.data))
              if (resp.data.userType === 0) {
                this.$router.push('/HomePage')
              } else if (resp.data.userType === 1) {
                this.$router.push('/Student/HomePage')
              }

              // 检索用户信息
              var userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
              console.log('登录成功,用户信息:')
              console.info(userInfo)
            } else {
              if (resp.responseCode === 20002) {
                this.$message.error({
                  message: '账号不存在或密码错误',
                  duration: 3000
                })
              } else if (resp.responseCode === 20003) {
                this.$message.error({
                  message: '验证码错误',
                  duration: 3000
                })
                this.changeValidateCode()
              } else {
                this.$message({
                  message: '服务器内部异常，请稍后再试',
                  type: 'warning',
                  duration: 3000
                })
              }
            }
          }
          )
        } else {
          // 表单未通过验证，不执行登录操作
          this.$message({
            message: '请检查账号、密码、验证码的格式后再登录',
            type: 'warning',
            duration: 3000
          })
        }
      })
    },
    resetForm: function () {
      this.ruleForm.isFormValid = false
      this.ruleForm.passWord = null
      this.ruleForm.accountNumber = null
      this.ruleForm.validateCode = null
    },
    changeValidateCode: function () {
      this.validateCodeUrl = 'http://localhost:8080/VerificationCode/getVerificationCode?timestamp=' + Date.now().toString()
    },
    goRegister: function () {
      this.$router.push('/register')
    },
    handleEnterKey (event) {
      // 检查按下的键是否是回车键
      if (event.key === 'Enter') {
        this.submitForm()
      }
    }
  },
  created () {
    if (sessionStorage.getItem('userInfo') !== null) {
      this.$router.push('/HomePage')
    }
  },
  mounted () {
    // 组件挂载时，添加全局键盘事件监听器
    window.addEventListener('keydown', this.handleEnterKey)
  },
  beforeDestroy () {
    // 组件销毁时，移除全局键盘事件监听器
    window.removeEventListener('keydown', this.handleEnterKey)
  }
  /* watch: {
    // 监听表单的验证状态，更新 isFormValid 的值
    ruleForm: {
      deep: true,
      handler (val) {
        this.$refs.ruleForm.validate((valid) => {
          this.ruleForm.isFormValid = valid
        })
      }
    }
  } */
}
</script>

<style lang="less" scoped>
.login-page {
  width: 100%;
  height: 100%;
  background: url("../../../static/img/login.png") center top no-repeat;
  background-size: cover;
  position: relative;

  .login-box {
    width: 400px;
    background-color: aliceblue;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    padding-right: 40px;
    padding-top: 20px;
    border-radius: 10%;

    h1 {
      text-align: center;
      margin-bottom: 20px;
      padding-left: 40px;
      font-size: 20px;
    }

    #el-button-a {
      margin-left: -55px; /* 向左平移 15px */
      text-align: center;
      border-radius: 5px;
      margin-right: 9px;
      padding-left: 32px;
      padding-right: 32px;
    }

    #el-button-b {
      margin-left: 9px; /* 向左平移 15px */
      margin-right: 9px;
      border-radius: 5px;
      text-align: center;
      padding-left: 32px;
      padding-right: 32px;
    }

    #el-button-c {
      margin-left: 9px;
      border-radius: 5px;
      text-align: center;
      padding-left: 32px;
      padding-right: 32px;
    }

    #validateCodeButton {
      height: 40px;
      width: 100%;
      margin-left: 20px;
      padding: 0;
    }

    .captcha-box {
      display: flex;
    }

    .validateCodeImg {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
